package per.turtle.gateway.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import per.turtle.common.core.constant.CacheConstants;
import per.turtle.common.core.utils.ServletUtils;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.redis.service.RedisService;
import per.turtle.gateway.config.properties.IgnoreWhiteProperties;
import per.turtle.system.dto.LoginUser;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 网关鉴权
 *
 * @author turtle
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private final static long EXPIRE_TIME = CacheConstants.TOKEN_EXPIRE * 60;

    /**
     * 排除过滤的 uri 地址，nacos自行添加
     */
    private final IgnoreWhiteProperties ignoreWhite;

    private final RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();

        // 跳过不需要验证的路径
        AntPathMatcher matcher = new AntPathMatcher();
        for (String white : ignoreWhite.getWhites()) {
            if (matcher.match(white, url)) {
                return chain.filter(exchange);
            }
        }

        String token = getToken(exchange.getRequest());
        if (StrUtil.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        LoginUser user = redisService.getCacheObject(CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, token));
        if (BeanUtil.isEmpty(user)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        String userid = user.getUserId();
        String username = user.getUsername();
        if (StrUtil.isBlank(userid) || StrUtil.isBlank(username)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置过期时间
        redisService.expire(CacheConstants.getCacheKey(CacheConstants.LOGIN_TOKEN_KEY, token), EXPIRE_TIME);
        // 设置用户信息到请求
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
                                               .header(CacheConstants.DETAILS_USERNAME, ServletUtils.urlEncode(username)).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

    @Override
    public int getOrder() {
        return -200;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(CacheConstants.HEADER);
        if (StrUtil.isNotEmpty(token) && Objects.requireNonNull(token).startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSONUtil.toJsonStr(CommonResult.error(msg)).getBytes());
        }));
    }

}